﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace BamiTech.AirServer
{
    class HTTPLikeResponse
    {
        private byte[] Body = new byte[0];
        private Dictionary<string, string> HeaderPairs= new Dictionary<string, string>();

        private Int32 StatusCode = 200;
        private string StatusMessage = "";
        private string Protocol = "";

        public HTTPLikeResponse(Int32 statusCode, string statusMessage, string protocol)
        {
            StatusCode = statusCode;
            StatusMessage = statusMessage;
            Protocol = protocol;
        }

        public void AddHeader(String key, string Value)
        {
            HeaderPairs.Add(key, Value);
        }

        public void SetBody(byte[] body)
        {
            if (body != null)
            {
                Body = body;
            }
            else
            {
                Body = new byte[0];
            }
        }

        public byte[] ToBytes()
        {
            int body_size = Body.Count();

            StringBuilder headers = new StringBuilder();
            headers.Append($"{Protocol} {StatusCode} {StatusMessage}\r\n");
            foreach(var pair in HeaderPairs)
            {
                headers.Append($"{pair.Key}: {pair.Value}\r\n");
            }
            headers.Append($"Content-Length: {Body.Length}\r\n");
            headers.Append("\r\n");

            byte[] header_buffer = UTF8Encoding.UTF8.GetBytes(headers.ToString());
            byte[] total_content = new byte[header_buffer.Length + Body.Length];

            Array.Copy(header_buffer, total_content, header_buffer.Length);
            Array.Copy(Body, 0, total_content, header_buffer.Length, Body.Length);
            return total_content;            
        }
    }
}
